package com.t194.controller;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;

@Controller
public class LoginController {

    @GetMapping("/login")
    public String login(){
        return "login";
    }

    @PostMapping("/login")
    public String login(String userCode,String password){
        UsernamePasswordToken token=new UsernamePasswordToken(userCode,password);
        Subject subject= SecurityUtils.getSubject();
        subject.login(token);
        return "redirect:/index";
    }
     //处理当前类的异常
    @ExceptionHandler(Exception.class)
    public String handleException(Exception ex,Model model){
        String error="default";
        if(ex instanceof UnknownAccountException){
            error="用户名或密码错误！";
        }else if(ex instanceof IncorrectCredentialsException){
            error="用户名或密码错误！";
        }else{
            error="程序出错，请联系管理员！";
        }
        System.out.println(error);
        model.addAttribute("error",error);
        return "login";
    }

}
